<?php

namespace app\common\logic;


abstract class BaseLogic
{

    /**
     * @var array<string,object>
     */
    private static $container = [];

    protected string $message = '';

    protected int $code = 0;

    public function getMessage(): string
    {
        return $this->message;
    }

    public function setMessage(string $message): bool
    {
        $this->message = $message;
        return false;
    }

    public function setMessageAndCode(string $message, int $code)
    {
        $this->message = $message;
        $this->code = $code;
        return false;
    }

    public function setCode(int $code)
    {
        $this->code = $code;
        return $this;
    }

    public function getCode(): int
    {
        return $this->code;
    }

    public static function instance()
    {
        //解析调用的类
        $classPath = explode('\\', static::class);
        if (!$classPath) {
            throw new \RuntimeException("类的路径错误");
        }
        $className = strtolower(array_pop($classPath));
        $instance = self::$container[$className] ?? null;
        if (!$instance) {
            //new该类
            $instance = self::$container[$className] = new static();
        }
        return $instance;
    }

    public static function __callStatic($name, $arguments)
    {
        $instance = self::instance();
        if (!method_exists($instance, $name)) {
            throw new \RuntimeException(sprintf("method[%s] not found in php file[%s]", $name, static::class));
        }
        return $instance->{$name}(...$arguments);
    }
}
